package com.unittec.drainage.provider.db;

import java.util.Date;

import com.unittec.drainage.provider.root.EntityRoot;
import com.unittec.drainage.provider.scope.ThreadLocalScope;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.unittec.drainage.sdk.root.common.FieldConstants;

/**
 * @author: trace
 * @date: 2019-05-24.
 * @Description:
 * @Email: tracenet@126.com
 */
public class MetaObjectHandlerImpl implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // TODO appid现在是固定的
        // this.setFieldValByName(FieldConstants.APP_ID, ThreadLocalScope.getAppId(), metaObject);
        // this.setFieldValByName(FieldConstants.TENANT_ID, ThreadLocalScope.getTenantId(), metaObject);
        if (metaObject.getOriginalObject() instanceof EntityRoot) {
            if (StringUtils.isBlank(((EntityRoot)metaObject.getOriginalObject()).getCreateUser())) {
                this.setFieldValByName(FieldConstants.CREATE_USER, ThreadLocalScope.getAuthData().getUser(),
                    metaObject);
            }
            if (((EntityRoot)metaObject.getOriginalObject()).getCreateTime() == null) {
                this.setFieldValByName(FieldConstants.CREATE_TIME, new Date(), metaObject);
            }
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.getOriginalObject() instanceof EntityRoot) {
            if (StringUtils.isBlank(((EntityRoot)metaObject.getOriginalObject()).getModifyUser())) {
                this.setFieldValByName(FieldConstants.MODIFY_USER, ThreadLocalScope.getAuthData().getUser(),
                    metaObject);
            }
        }

        this.setFieldValByName(FieldConstants.MODIFY_TIME, new Date(), metaObject);
    }
}
